<script>
    import { filesUpload, onlinePreview } from "@/api/common";
    import { base64Encode } from '@zkey-webapp/general';
    // 操作按钮枚举
    const OperBtnKeyEnum = {
        // 上传
        UPLOAD: 'UPLOAD',
        // 复制上传
        COPY_UPLOAD: 'COPY_UPLOAD',
        // 下载
        DOWNLOAD: 'DOWNLOAD',
        // 预览
        VIEW: 'VIEW',
        // 删除文件
        DELETE: 'DELETE',
        // 清空文件
        CLEAR: 'CLEAR',
        props: {
            UPLOAD: '上传',
            COPY_UPLOAD: '上传',
            DOWNLOAD: '下载',
            VIEW: '预览',
            DELETE: '移除',
            CLEAR: '移除',
        },
        toStr(key) {
            key = "" + key;
            return OperBtnKeyEnum.props[key] || "";
        },
    }
    // 文件列表上传
    export default {
        name: "FileTable",
        OperBtnKeyEnum,
        props: {
            data: {
                type: Array,
                default: () => [],
            },
            // 自定义列表项
            columns: {
                type: Array,
            },
            // 操作行的宽度
            operWidth:  {
                type: String,
                default: () => '150px',
            },
            // 允许的文件类型  https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept
            accept: {
                type: String,
                default: () => '*',
            },
            scroll: {
                type: Object,
            },
            // 业务编码
            bizType: Number,
            disabled: {
                type: Boolean,
            }
        },
        components: {
        },
        data() {
            return {
                fileList: [], // 文件列表
            }
        },
        created() {
            this.init();
        },
        watch: {
            data() {
                this.initData();
            },
        },
        computed: {
            infoColumns() {
                const defaultColumns = [];
                if (this.columns && this.columns.length > 0) {
                    defaultColumns.push(...this.columns);
                    defaultColumns.push({
                        title: '操作',
                        width: this.operWidth,
                        scopedSlots: { customRender: 'action' },
                    });
                } else {
                    defaultColumns.push(...[{
                        title: '文件名称',
                        width: '180px',
                        dataIndex: 'fileName',
                    },
                    {
                        title: '上传时间',
                        width: '160px',
                        dataIndex: 'uploadTime',
                    },
                    {
                        title: '操作',
                        width: this.operWidth,
                        scopedSlots: { customRender: 'action' },
                    }]);
                }
                return defaultColumns;
            },
        },
        render() {
            const { infoColumns, fileList, renderBtns, scroll } = this;
            return (
                   <div class="file-table">
                        <a-table
                            ref="table"
                            row-key="index"
                            columns={infoColumns}
                            data-source={fileList}
                            pagination={false}
                            scroll={scroll}
                            scopedSlots={{
                                ...this.$scopedSlots,
                                action: props => {
                                    return (
                                        <div>
                                            {renderBtns(props)}
                                        </div>
                                    );
                                },
                            }}
                        >
                        </a-table>
                    </div>
            );
        },
        methods: {
            async init() {
                this.initData();
            },
            initData() {
                this.fileList.splice(0);
                if (this.data && this.data.length > 0) {
                    this.fileList.push(...this.data);
                    this.resetItemIndex();
                }
            },
            // 渲染按钮
            renderBtns(item){
                const {
                    checkViewBtn,
                    itemChange,
                    handleUpload,
                    handleCopyUpload,
                    handleViewItem,
                    handleDownloadItem,
                    handleDelItem,
                    handleClearItem,
                    handleBtnClick,
                    accept,
                    disabled
                } = this;
                const { operBtns } = item;
                const operBtnOpts = [];
                operBtns.forEach((n) => {
                    if (typeof n === "string") {
                        operBtnOpts.push({
                            key: n,
                            label: OperBtnKeyEnum.toStr(n),
                        });
                    } else if (typeof n === "object" && n !== null) {
                        if (!n.label) {
                            n.label = OperBtnKeyEnum.toStr(n.key);
                        }
                        operBtnOpts.push(n);
                    }
                });
                // console.log(operBtns);
                return operBtnOpts.map((i, index)=>{
                    if (i.key === OperBtnKeyEnum.UPLOAD) {
                        // 上传
                        return (<a-upload disabled={disabled} accept={i.accept || accept} v-show={i.show || !item.fileUrl} customRequest={(fileParam)=>handleUpload(fileParam,i)} data={item} show-upload-list={false} onChange={()=> itemChange(i, item)} >
                            <zk-btn icon={i.icon || 'edit'} >{i.label}</zk-btn>
                        </a-upload>)
                    } else if (i.key === OperBtnKeyEnum.COPY_UPLOAD) {
                        // 复制上传
                        return (<a-upload disabled={disabled} accept={i.accept || accept} v-show={i.show || !item.fileUrl} customRequest={handleCopyUpload} data={item} show-upload-list={false} onChange={()=> itemChange(i, item)} >
                            <zk-btn icon={i.icon || 'edit'} >{i.label}</zk-btn>
                        </a-upload>)
                    } else if (i.key === OperBtnKeyEnum.VIEW) {
                        // 预览
                        return (<span v-show={checkViewBtn(item.fileUrl,item.fileName)}>
                            <zk-btn onClick={() => handleViewItem(i, item) } icon={i.icon || 'eye'}>{i.label}</zk-btn>
                            <a-divider type="vertical" v-show={index !== operBtnOpts.length - 1 } />
                        </span>);
                    } else if (i.key === OperBtnKeyEnum.DOWNLOAD) {
                        // 下载
                        return (<span v-show={item.fileUrl}>
                            <zk-btn onClick={() => handleDownloadItem(i, item)} icon={i.icon || 'download'} >{i.label}</zk-btn>
                            <a-divider type="vertical" v-show={index !== operBtnOpts.length - 1 } />
                        </span>);
                    } else if (i.key === OperBtnKeyEnum.DELETE) {
                        // 移除
                        return (<span v-show={item.fileUrl}>
                            <zk-btn onClick={() => handleDelItem(i, item)} icon={i.icon || 'delete'} >{i.label}</zk-btn>
                            <a-divider type="vertical" v-show={index !== operBtnOpts.length - 1 } />
                        </span>);
                    } else if (i.key === OperBtnKeyEnum.CLEAR) {
                        // 移除
                        return (<span v-show={item.fileUrl}>
                            <zk-btn onClick={() => handleClearItem(i, item)} icon={i.icon || 'delete'} >{i.label}</zk-btn>
                            <a-divider type="vertical" v-show={index !== operBtnOpts.length - 1 } />
                        </span>);
                    } else {
                        // 自定义按钮
                        return (<span v-show={i.show}>
                            <zk-btn onClick={() => handleBtnClick(i, item)} icon={i.icon || 'edit'} >{i.label}</zk-btn>
                        </span>);
                    }
                });
            },
            // 删除列表项
            handleDelItem(btn, item) {
                this.fileList.splice(item.index, 1);
                this.resetItemIndex();
                this.$emit('del', item, this.getFileList());
                this.handleBtnClick(btn. item);
            },
            // 清除列表项
            handleClearItem(btn, item) {
                item.fileId = null;
                item.fileUrl = null;
                item.fileName = null;
                item.uploadTime = null;
                this.$emit('clear', item, this.getFileList());
                this.handleBtnClick(btn. item);
            },
            // 自定义按钮点击事件
            handleBtnClick(btn, item) {
                this.$emit('click', btn, item);
            },
            // 重置列表项索引
            resetItemIndex() {
                this.fileList.forEach((item, index) => {
                    item.index = index;
                });
            },
            // 当前操作的item
            itemChange(btn, item) {
                this.item = item;
                this.handleBtnClick(btn, item);
            },
            // 上传
            handleUpload(fileParam, btnOpt) {
                this.loading = true;
                const param = new FormData();
                param.append('file', fileParam.file)
                // 添加上传文件资源类型 
                param.append('resourceBizType', this.bizType);
                // this.$emit('beforeUpload', param);
                filesUpload(param)
                .then((result) => {
                    this.loading = false;
                    this.item.fileId = result.fileId;
                    this.item.fileUrl = result.fileUrl;
                    this.item.fileName = fileParam.file.name;
                    this.item.uploadTime = result.uploadTime;
                    this.$emit("ok", this.item, this.getFileList(), btnOpt);
                })
                .catch((error) => {
                    console.log("上传失败！", error);
                    this.loading = false;
                    this.$emit("cancel", error, btnOpt);
                });
            },
            // 复制上传
            handleCopyUpload(fileParam) {
                this.loading = true;
                const param = new FormData();
                param.append('file', fileParam.file)
                // 添加上传文件资源类型 
                param.append('resourceBizType', this.bizType);
                // this.$emit('beforeUpload', param);
                filesUpload(param)
                .then((result) => {
                    this.loading = false;
                    const item = { ...this.item };
                    item.fileId = result.fileId;
                    item.fileUrl = result.fileUrl;
                    item.fileName = fileParam.file.name;
                    item.uploadTime = result.uploadTime;
                    this.fileList.splice(item.index, 0, item);
                    this.resetItemIndex();
                    this.$emit("ok", item, this.getFileList());
                })
                .catch((error) => {
                    console.log("上传失败！", error);
                    this.loading = false;
                    this.$emit("cancel", error);
                });
            },
            // 返回全部文件列表
            getFileList(filter){
                if (filter) {
                    const list =  this.fileList.filter(i =>{
                        // key为空并且fileId为空的则不返回
                        return  i.key || i.fileId;
                    });
                    return list;
                } else {
                    return this.fileList.map(n => n);
                }
            },
            // 预览文件
            handleViewItem(btn, item) {
                this.handleBtnClick(btn. item);
                // 构造URL
                const url = onlinePreview(encodeURIComponent(base64Encode(item.fileUrl)));
                window.open(url);
            },
            // 是否显示预览按钮
            checkViewBtn(fileUrl, fileName){
                return fileUrl && this.supportFile(fileName);
            },
            // 预览支持的文件
            supportFile(fileName) {
                const fileNameList = fileName.split('.');
                if (fileNameList.length !== 2) {
                    return false;
                }
                const extendName = fileNameList[1].toLowerCase();
                if ('ppt,pptx,pdf,xlsx,xls,doc,docx,jpg,jpeg,png,gif,mp3,mp4,flv'.indexOf(extendName) > -1) {
                    return true;
                }
                return false;
            },
            // 下载文件
            handleDownloadItem(btn, item) {
                this.handleBtnClick(btn. item);
                window.open(item.fileUrl);
            },
        }
    }
</script>
<style lang="less">
.file-table {
    .required-text{
        color: #FF0000;
    }
}
</style>